from rest_framework import serializers
from users.models import User
from django.contrib.auth.hashers import make_password

class UserModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = [
            'id', 
            'username', 
            'mobile', 
            'email',
            'password' # 补充password用于反序列化校验和新建保存
        ]
        # 为字段增加约束
        extra_kwargs = {
            'password':{'write_only': True, 'min_length': 8, 'max_length': 20}, 
            'username':{'min_length': 2, 'max_length': 20}
        }
        # 方法1
        # 新建保存的过程中介入来密码加密和is_staff设置为True
        def create(self, validated_data):
            # is_staff前端没传，默认是false
            validated_data['is_staff'] =True
            # create_user能加密密码创建对象
            instance = User.objects.create_user(validated_data)
            return instance

        # 方法2
        # 校验的过程中介入来密码加密和is_staff设置为True
        # def validate(self, attrs):
        #     attrs['is_staff'] = True
        #     # 拿到未加密密码
        #     row_password = attrs.get('password')
        #     # 把密码加密
        #     jiami_password = make_password(row_password)
        #     # 赋值回去
        #     attrs['password'] = jiami_password
        #     return attrs


        